package com.sxkj.service.base;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sxkj.entity.base.BaseMapper;
import com.sxkj.entity.base.DataEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Service基类
 * @version 2019-11-29
 */
@Transactional(readOnly = true,propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public abstract class BaseService<D extends BaseMapper<T>,T extends DataEntity> {

	protected static final int DEFAULT_PAGE_SIZE = 20;
	@Autowired
	protected D baseMapper;

	/**
	 * 日志对象
	 */
	protected Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 获取单条数据
	 * @param id
	 * @return
	 */
	public T get(String id) throws Exception{
		return baseMapper.get(id);
	}

	/**
	 * 获取单条数据
	 * @param entity
	 * @return
	 */
	public T get(T entity) throws Exception{
		return baseMapper.get(entity);
	}

	/**
	 * 查询列表数据
	 * @param entity
	 * @return
	 */
	public List<T> findList(T entity) throws Exception{
		return baseMapper.findList(entity);
	}

	/**
	 * 查询分页数据
	 * @param entity
	 * @param pageSize
	 * @param pageNum
	 * @return
	 */
	public PageInfo findPage(T entity, Integer pageSize, Integer pageNum) throws Exception{
		PageHelper.startPage(pageNum<=0?1:pageNum,pageSize<=0?DEFAULT_PAGE_SIZE:pageSize);
		return new PageInfo(baseMapper.findList(entity));
	}

	/**
	 * 保存数据（插入或更新）
	 * @param entity
	 */
	@Transactional(rollbackFor = Exception.class)
	public void save(T entity) throws Exception{
		if (entity.getIsNewRecord()){
			entity.preInsert();
			baseMapper.insert(entity);
		}else{
			entity.preUpdate();
			baseMapper.update(entity);
		}
	}

	/**
	 * 删除数据
	 * @param entity
	 */
	@Transactional(rollbackFor = Exception.class)
	public void delete(T entity) throws Exception{
		baseMapper.delete(entity);
	}

}
